package com.hy.mybatisplus.config;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 分页工具类
 *
 * @author hy
 * @date 2020-09-28
 */

@JsonInclude(JsonInclude.Include.NON_NULL)
@Data
public class PageDto<T> {

    /**
     * 页数
     */
    private int page;

    /**
     * 每页大小
     */
    private int pageSize;

    /**
     * 排序字段
     */
    private String sortName;

    /**
     * 排序类型 ASC,DESC
     */
    private String sortType;

    /**
     * 工具类转换成Page对象
     * <p>
     * {@link Page}
     *
     * @return
     */
    public IPage<T> getPageUtil() {
        List<OrderItem> orderItems = new ArrayList<>();
        Page<T> page = new Page<T>();
        if (this.page == 0) {
            page.setCurrent(1);
        } else {
            page.setCurrent(this.page);
            //        page.setLimit((this.page - 1) * this.pageSize);
        }
        if (this.pageSize == 0) {
            this.pageSize = Integer.MAX_VALUE;
        } else {
            page.setSize(pageSize);

        }
        if (StringUtils.isNotEmpty(sortName)){
            if ("ASC".equalsIgnoreCase(sortType)) {
                orderItems.add(OrderItem.asc(sortName));
            } else {
                orderItems.add(OrderItem.desc(sortName));
            }
            page.setOrders(Arrays.asList(OrderItem.asc(sortName)));
        }
        return page;
    }
}